package com.yoomiito.app.ui.my.remain.withdraw

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.PopupWindow
import androidx.core.app.ActivityCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.scrat.app.selectorlibrary.ImageSelector
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.my.ApplyInfo
import com.yoomiito.app.utils.AllUtils
import com.yoomiito.app.utils.ImageLoader
import com.yoomiito.app.utils.YMToast
import com.yoomiito.app.widget.dialog.CustomDialog1
import kotlinx.android.synthetic.main.activity_add_withdraw.btn_delete
import kotlinx.android.synthetic.main.activity_add_withdraw.btn_submit
import kotlinx.android.synthetic.main.activity_add_withdraw.et_account
import kotlinx.android.synthetic.main.activity_add_withdraw.et_name
import kotlinx.android.synthetic.main.activity_add_withdraw.et_remark
import kotlinx.android.synthetic.main.activity_add_withdraw.iv_photo
import kotlinx.android.synthetic.main.activity_add_withdraw.ll_way
import kotlinx.android.synthetic.main.activity_add_withdraw.tv_account
import kotlinx.android.synthetic.main.activity_add_withdraw.tv_code
import kotlinx.android.synthetic.main.activity_add_withdraw.tv_way
import kotlinx.android.synthetic.main.title_bar.iv_back_left
import kotlinx.android.synthetic.main.title_bar.tv_center
import java.io.File

/**
 */
class AddWithdrawActivity : BaseActivity<AddWithdrawPresenter>() {
    private var picPath: String? = null
    private val REQUEST_SELECT_IMAGES_CODE = 7
    private val REQUEST_PHOTO_CODE = 8
    private var type: Int = 1
    private var applyInfo: ApplyInfo? = null
    private var mCustomDialog: CustomDialog1? = null
    private var fromType: Int = 1

    companion object {
        fun start(context: Context,fromType : Int) {
            val intent = Intent(context, AddWithdrawActivity::class.java)
            intent.putExtra("applyInfo", ApplyInfo())
            intent.putExtra("fromType", fromType)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_add_withdraw

    override fun newP(): AddWithdrawPresenter = AddWithdrawPresenter(App.mAppConfig)


    override fun initData(savedInstanceState: Bundle?) {
        initView()
    }

    private fun initView() {
        iv_back_left.setOnClickListener { finish() }
        tv_center.text = "添加提现方式"

        applyInfo = intent.getSerializableExtra("applyInfo") as ApplyInfo
        fromType =  intent.getIntExtra("fromType",1)
        if (applyInfo?.id?.isEmpty() == false) {
            et_account.setText(applyInfo?.accountNumber.toString())
            et_remark.setText(applyInfo?.remark)
            et_name.setText(applyInfo?.userName)
            ImageLoader.getInstance().into(this, applyInfo?.codeUrl, iv_photo)
            tv_way.text = applyInfo?.typeStr
            p.setmCurrentPhotoPath(applyInfo?.codeUrl)
            btn_delete.visibility = View.VISIBLE
        } else {
            btn_delete.visibility = View.GONE
        }
        iv_photo.setOnClickListener {
            val permissions = arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            var sb: StringBuilder? = null
            for (permission in permissions) {
                if (ActivityCompat.checkSelfPermission(
                        this,
                        permission!!
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    if (sb == null) {
                        sb = StringBuilder()
                    }
                    val str = AllUtils.permissionTipMap(permission)
                    if (sb.indexOf(str) == -1) {
                        if (!TextUtils.isEmpty(sb)) {
                            sb.append("\n\n")
                        }
                        sb.append(str)
                    }
                }
            }
            if (sb == null || TextUtils.isEmpty(sb)) {
                AllUtils.requestPermission(
                    this@AddWithdrawActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA
                )
                    .subscribe { aBoolean: Boolean ->
                        if (aBoolean) {
                            showPopueWindow()
                        } else {
                            YMToast.showText("请打开您的相册、相机使用权限")
                        }
                    }
            } else {
                if (mCustomDialog == null) {
                    mCustomDialog = CustomDialog1(
                        this
                    ) {
                        AllUtils.requestPermission(
                            this@AddWithdrawActivity,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA
                        )
                            .subscribe { aBoolean: Boolean ->
                                if (aBoolean) {
                                    showPopueWindow()
                                } else {
                                    YMToast.showText("请打开您的相册、相机使用权限")
                                }
                            }
                    }
                }
                mCustomDialog?.setContent(sb.toString())
                mCustomDialog?.show()
            }
        }
        ll_way.setOnClickListener { showWayWindow() }
        btn_submit.setOnClickListener {
            applyInfo?.type = type
            applyInfo?.codeUrl = p.getmCurrentPhotoPath()
            applyInfo?.accountNumber = et_account.text.toString()
            applyInfo?.remark = et_remark.text.toString()
            applyInfo?.userName = et_name.text.toString()
            p.accountInsert(applyInfo!!)
        }
        btn_delete.setOnClickListener {
            applyInfo?.id?.let { it1 -> p.accountDelete(it1) }
        }
    }

    private fun showPopueWindow() {
        val popView = View.inflate(this, R.layout.popupwindow_camera_need, null)
        val bt_album = popView.findViewById<View>(R.id.btn_pop_album) as Button
        val bt_camera = popView.findViewById<View>(R.id.btn_pop_camera) as Button
        val bt_cancle = popView.findViewById<View>(R.id.btn_pop_cancel) as Button
        //获取屏幕宽高
        val weight = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels * 1 / 3
        val popupWindow = PopupWindow(popView, weight, height)
        //        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.isFocusable = true
        //点击外部popueWindow消失
        popupWindow.isOutsideTouchable = true
        bt_album.setOnClickListener {
            val i = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            //                startActivityForResult(i, REQUEST_SELECT_IMAGES_CODE);
            //相册
            ImageSelector.show(context, REQUEST_SELECT_IMAGES_CODE, 1)
            popupWindow.dismiss()
        }
        bt_camera.setOnClickListener {
            p.takeCamera(REQUEST_PHOTO_CODE)
            popupWindow.dismiss()
        }
        bt_cancle.setOnClickListener { popupWindow.dismiss() }
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener {
            val lp = window.attributes
            lp.alpha = 1.0f
            window.attributes = lp
        }
        //popupWindow出现屏幕变为半透明
        val lp = window.attributes
        lp.alpha = 0.5f
        window.attributes = lp
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50)
    }


    private fun showWayWindow() {
        val popView = View.inflate(this, R.layout.popupwindow_way, null)
        val bt_album = popView.findViewById<View>(R.id.btn_pop_album) as Button
        val bt_camera = popView.findViewById<View>(R.id.btn_pop_camera) as Button
        val bt_cancle = popView.findViewById<View>(R.id.btn_pop_cancel) as Button
        //获取屏幕宽高
        val weight = resources.displayMetrics.widthPixels
        val height = resources.displayMetrics.heightPixels * 1 / 3
        val popupWindow = PopupWindow(popView, weight, height)
        //        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.isFocusable = true
        //点击外部popueWindow消失
        popupWindow.isOutsideTouchable = true
        bt_album.setOnClickListener {
            type = 2
            tv_way.text = "支付宝"
            tv_account.text = "支付宝账号"
            tv_code.text = "支付宝收款码"
            popupWindow.dismiss()
        }
        bt_camera.setOnClickListener {
            type = 1
            tv_way.text = "微信"
            tv_account.text = "微信账号"
            tv_code.text = "微信收款码"
            popupWindow.dismiss()
        }
        bt_cancle.setOnClickListener { popupWindow.dismiss() }
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener {
            val lp = window.attributes
            lp.alpha = 1.0f
            window.attributes = lp
        }
        //popupWindow出现屏幕变为半透明
        val lp = window.attributes
        lp.alpha = 0.5f
        window.attributes = lp
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            val imagePaths = ImageSelector.getImagePaths(data)
            picPath = imagePaths[0]
            val requestOptions = RequestOptions()
            requestOptions.placeholder(R.drawable.goods_default)
            val file = File(picPath)
            Glide.with(App.getApplication()).load(file).apply(requestOptions).into(iv_photo)
            p.uploadPhotos(picPath)
        } else if (requestCode == REQUEST_PHOTO_CODE && resultCode == RESULT_OK) {
            p.uploadPhotos(picPath)
            picPath = p.getmCurrentPhotoPath()
            val requestOptions = RequestOptions()
            requestOptions.placeholder(R.drawable.goods_default)
            val file = File(picPath)
            Glide.with(App.getApplication()).load(file).apply(requestOptions).into(iv_photo)
        }
    }


}